<?php

namespace app\api\controllers;

use app\api\models\MainModel;
use cm;
use Yii;
use app\api\core\BaseController;
use app\api\core\CreateUuid;
use app\api\core\wechat\wxAction;
use app\api\core\wechat\wxUser;

use yii\helpers\Url;
use app\api\core\wechat\wxReply;
define('LOGPATH', Yii::getAlias('@runtime/wechat/log'));

class MainController extends BaseController
{
    public  $layout =  false;
    public function actionDoc()
    {
        return $this->render('doc');
    }
    //component_verify_ticket:接受微信ticket:授权信息
    public function actionIndex()
    {
        //以下三个变量，自己去开放平台上管理中心根据实际情况填写。
        $encodingAesKey = Yii::$app->params['wechat']['encodingAesKey'];
        $token = Yii::$app->params['wechat']['token'];
        $appId = Yii::$app->params['wechat']['appid'];

        $timeStamp  = empty($_GET['timestamp'])     ? ""    : trim($_GET['timestamp']) ;
        $nonce      = empty($_GET['nonce'])     ? ""    : trim($_GET['nonce']) ;
        $msg_sign   = empty($_GET['msg_signature']) ? ""    : trim($_GET['msg_signature']) ;
        $encryptMsg = file_get_contents('php://input');
        $pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);


        $xml_tree = new \DOMDocument();
        $xml_tree->loadXML($encryptMsg);
        $array_e = $xml_tree->getElementsByTagName('Encrypt');
        $encrypt = $array_e->item(0)->nodeValue;

        $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
        $from_xml = sprintf($format, $encrypt);
        YII_DEBUG && $this->logResult('/form.log', $from_xml);

        // 第三方收到公众号平台发送的消息
        $msg = '';
        $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);

        if ($errCode == 0) {
            YII_DEBUG && $this->logResult('/msg.log','解密后文件：'.$msg);

            $xmlArray = \Auth::xmlToArray($msg);
            YII_DEBUG && $this->logResult('/msg.log','转换成数组转json：'.json_encode($xmlArray));
            $array_type_value = $xmlArray['InfoType'];

            $appId = $xmlArray['AppId'];
            switch ($array_type_value) {
                case 'component_verify_ticket':
                    $component_verify_ticket = $xmlArray['ComponentVerifyTicket'];
                    //写入数据库：
                    $result = Cm::$db->one("SELECT id FROM `scrm_weixin_three_account` WHERE appid='{$appId}'");
                    if (!$result) {
                        Cm::$db->insert('scrm_weixin_three_account', [
                            'id'=>(new CreateUuid())->toString(),
                            'appid'=>$appId,
                            //'appsecret'=>'',
                            'encodingAesKey'=>$encodingAesKey,
                            'token'=>$token,
                            'component_verify_ticket'=>$component_verify_ticket,
                        ]);
                    } else {
                        Cm::$db->update('scrm_weixin_three_account', [
                            'component_verify_ticket'=>$component_verify_ticket,
                        ], "appid='{$appId}'");
                    }

                    file_put_contents(LOGPATH.'/ticket.log', $component_verify_ticket);
                    YII_DEBUG && $this->logResult('/msgmsg.log','解密后的component_verify_ticket是：'.$component_verify_ticket);
                    break;
                case 'unauthorized':#取消授权
                    $authorizerAppid = $xmlArray['AppId'];

                    $result = Cm::$db->one("SELECT id FROM `scrm_weixin_account` WHERE accountappid='{$authorizerAppid}'");
                    if ($result) {
                        Cm::$db->update('scrm_weixin_account', [
                            'status'=>0
                        ], "accountappid='{$authorizerAppid}'");
                    }
                    break;
                case 'authorized' :
                    // 授权
                    YII_DEBUG && $this->logResult('/auth.log','转换成数组转json：'.json_encode($xmlArray));
                    break;

                case 'updateauthorized':
                    break;

            }
            echo 'success';

        } else {
            YII_DEBUG && $this->logResult('/error.log','解密后失败：'.$errCode);
            print($errCode . "\n");
        }
    }

    /**
     * 写日志：
     * @param $path
     * @param $data
     */
    public function logResult($path, $data)
    {

        if (!is_dir(LOGPATH)) {
            mkdir(LOGPATH, 0777, true);
        }

        file_put_contents(LOGPATH.$path, '[时间：'.date('Y-m-d  H:i:s',time()).']，结果：'.$data."\r\n",FILE_APPEND);
    }

    /**
     * 微信事件接受[全网检测]
     */
    public function actionWx_auth()
    {

        YII_DEBUG && $this->logResult('/auth_get.log','微信事件接受：'.json_encode($this->get()));

        $appid = ltrim($this->get('appid'), '/');

        $result = Cm::$db->one("SELECT id FROM `scrm_weixin_account` WHERE accountappid='{$appid}'");
        if ($result) {

        }
        YII_DEBUG && $this->logResult('/auth_get.log','微信事件$appid：'.$appid);
        $data   = \Auth::cryptXmlToArray('auth');
        YII_DEBUG && $this->logResult('/Array.log','转换成json：'.json_encode($data));

        if (!$data) {
            echo 'error';
        }

        $openid = $data['FromUserName'];
        $accountNumber = $data['ToUserName'];

        $wxchat = new wxReply($appid, $openid, $accountNumber);

        $type = '';
        if ($data['MsgType']==='event') {
            //模拟登陆
            if ($data['Event'] != 'unsubscribe') {
                $type = $data['MsgType'].'-'.$data['Event'];
                $wxchat->writeLoginLog($openid, $type, $data, $data['Event']=='subscribe' ? true : false);
            }
            switch ($data['Event']) {
                case 'subscribe':#关注
                    $wxchat->subscribe();
                    break;
                case 'unsubscribe':#取消关注
                    $wxchat->unsubscribe();
                    break;
                case 'click':#点击菜单
                    break;
                case 'view':#点击菜单跳转链接时的事
                    break;
            }

        } else {
            //模拟登陆
            $type = '接受用户消息：'.$data['MsgType'];
            $wxchat->writeLoginLog($openid, $type, $data);
            //scrm_weixin_message:接收消息
            switch ($data['MsgType']) {

                case 'text':
                    $wxchat->receiveText($data, $result['id']);
                    break;
                case 'image':
                    $wxchat->receiveImage($data, $result['id']);
                    break;
                case 'voice':
                    $wxchat->receiveVoice($data, $result['id']);
                    break;
                case 'video':
                    $wxchat->receiveVideo($data, $result['id']);
                    break;
                case 'music':
                    break;
                case 'location':#位置
                    break;
                case 'file':#文件
                    break;
                default:

                    break;
            }


        }


    }

    public function actionWx_auth_ceshi()
    {
        //YII_DEBUG && $this->logResult('/auth_get.log','微信事件接受：'.json_encode($this->get()));

        $appid ='wx2c076b140ffffb59'; //ltrim($this->get('appid'), '/');

        $result = Cm::$db->one("SELECT id FROM `scrm_weixin_account` WHERE accountappid='{$appid}'");
        if ($result) {

        }
        YII_DEBUG && $this->logResult('/auth_get.log','微信事件$appid：'.$appid);
        $str = "<xml><ToUserName><![CDATA[gh_3eaae89c77aa]]></ToUserName>
<FromUserName><![CDATA[oTVrs0dVYSsogHNPYIr8wdPdY9bQ]]></FromUserName>
<CreateTime>1534240246</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[unsubscribe]]></Event>
<EventKey><![CDATA[]]></EventKey>
</xml>";
        $data   = \Auth::xmlToArray($str);



        YII_DEBUG && $this->logResult('/Array.log','转换成json：'.json_encode($data));

        if (!$data) {
            echo 'error';
        }

        $openid = $data['FromUserName'];
        $accountNumber = $data['ToUserName'];

        $wxchat = new wxReply($appid, $openid, $accountNumber);


        if ($data['MsgType']==='event') {
            switch ($data['Event']) {
                case 'subscribe':#关注
                    $wxchat->subscribe();
                    break;
                case 'unsubscribe':#取消关注

                    $wxchat->unsubscribe();
                    break;
            }
        } else {
            switch ($data['MsgType']) {

                case 'text':
                    break;
                case 'image':
                    break;
                case 'voice':
                    break;
                case 'video':
                    break;
                case 'music':
                    break;
                default:

                    break;
            }
        }

    }

    /**
     * 测试
     */
    public function actionText()
    {
        //以下三个变量，自己去开放平台上管理中心根据实际情况填写。
        $encodingAesKey = Yii::$app->params['wechat']['encodingAesKey'];
        $token = Yii::$app->params['wechat']['token'];
        $appId = Yii::$app->params['wechat']['appid'];

        $timeStamp  = empty($_GET['timestamp'])     ? ""    : trim($_GET['timestamp']) ;
        $nonce      = empty($_GET['nonce'])     ? ""    : trim($_GET['nonce']) ;
        $msg_sign   = empty($_GET['msg_signature']) ? ""    : trim($_GET['msg_signature']) ;
//        $encryptMsg = file_get_contents('php://input');
//        $pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);
//
//
//        $xml_tree = new \DOMDocument();
//        $xml_tree->loadXML($encryptMsg);
//        $array_e = $xml_tree->getElementsByTagName('Encrypt');
//        $encrypt = $array_e->item(0)->nodeValue;
//
//        $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
//        $from_xml = sprintf($format, $encrypt);
//        $this->logResult('/form.log', $from_xml);

        // 第三方收到公众号平台发送的消息
        $msg = '<xml><AppId><![CDATA[wx78b5d74b949d609f]]></AppId>
<CreateTime>1533007105</CreateTime>
<InfoType><![CDATA[component_verify_ticket]]></InfoType>
<ComponentVerifyTicket><![CDATA[ticket@@@LW0oyucDO4lAXP480yB6BvLTnLGRZLH8aXBWFk7hGWRK3HOTOhO41SR0YqDjs3II-z0qxWdLRU2UfYJZjFBJ-Q]]></ComponentVerifyTicket>
</xml>';
        $errCode =0; //$pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);

        if ($errCode == 0) {
            $this->logResult('/msg.log','解密后文件：'.$msg);


            $xmlArray = \Auth::xmlToArray($msg);

            $this->logResult('/msg.log','转换成数组转json：'.json_encode($xmlArray));
            $array_type_value = $xmlArray['InfoType'];


            switch ($array_type_value) {
                case 'component_verify_ticket':
                    $component_verify_ticket = $xmlArray['ComponentVerifyTicket'];
                    //写入数据库：
                    $result = Cm::$db->one("SELECT id FROM `scrm_weixin_three_account` WHERE appid='{$appId}'");
                    if (!$result) {
                        Cm::$db->insert('scrm_weixin_three_account', [
                            'appid'=>$appId,
                            //'appsecret'=>'',
                            'encodingAesKey'=>$encodingAesKey,
                            'token'=>$token,
                            'component_verify_ticket'=>$component_verify_ticket,
                        ]);
                    } else {
                        Cm::$db->update('scrm_weixin_three_account', [
                            'component_verify_ticket'=>$component_verify_ticket,
                        ], "appid='{$appId}'");
                    }

                    file_put_contents(LOGPATH.'/ticket.log', $component_verify_ticket);
                    $this->logResult('/msgmsg.log','解密后的component_verify_ticket是：'.$component_verify_ticket);
                    break;
                case 'unauthorized':#取消授权
                    $authorizerAppid = $xmlArray['AppId'];

                    $result = Cm::$db->one("SELECT id FROM `scrm_weixin_account` WHERE accountappid='{$authorizerAppid}'");
                    if ($result) {
                        Cm::$db->update('weixin_account', [
                            'status'=>0
                        ], "accountappid='{$authorizerAppid}'");
                    }
                    break;
                case 'authorized' :                 // 授权
                    break;
            }
            echo 'success';

        } else {
            $this->logResult('/error.log','解密后失败：'.$errCode);
            print($errCode . "\n");
        }
    }

    /**
     * 微信回调地址
     */
    public function actionWx_back()
    {
        ob_start();
        $options = [
            'component_appid' => '',
            'component_appsecret' => '',
            'component_verify_ticket'=>''
        ];

        $authCode = $this->get('auth_code');
        $cid = $this->get('cid', 0);

        //获取ticket
        $appId = Yii::$app->params['wechat']['appid'];

        $ticket = Cm::$db->one("SELECT component_verify_ticket,appsecret FROM `scrm_weixin_three_account` WHERE appid='{$appId}'");
        if (!$ticket) {
            echo 'component_verify_ticket:不存在';exit;
        }

        $options['component_appid'] = $appId;
        $options['component_appsecret'] = $ticket['appsecret'];
        $options['component_verify_ticket'] = $ticket['component_verify_ticket'];
        $auth = new \Auth($options);
        $auth->get_authorization_info($authCode, $cid,true);//获取授权方信息

        $app_url = Yii::$app->params['app_url']."?d=sync";

        header("Location:{$app_url}");exit;
        //获取数据 并 跳转页面：
    }

    /**
     * 测试数据：
     * @return string
     */
    public function actionWx_auth_test()
    {
        $options = [
            'component_appid' => '',
            'component_appsecret' => '',
            'component_verify_ticket'=>''
        ];

        $authCode = $this->get('auth_code');

        //获取ticket
        $appId = Yii::$app->params['wechat']['appid'];

        $ticket = Cm::$db->one("SELECT component_verify_ticket,appsecret FROM `scrm_weixin_three_account` WHERE appid='{$appId}'");
        if (!$ticket) {
            echo 'component_verify_ticket:不存在';exit;
        }

        $options['component_appid'] = $appId;
        $options['component_appsecret'] = $ticket['appsecret'];
        $options['component_verify_ticket'] = $ticket['component_verify_ticket'];
        $auth = new \Auth($options);

        if (empty($authCode)) {
            //授权
            $code = $auth->get_auth_code();
            $url = $auth->getRedirect(Yii::$app->params['auth_back_url']."?cid=1", $code);

            return $this->render('wx/auth', ['url'=>$url]);
        } else {
            //此外示例代授权回调后获取公众号信息
            $wechats_info = $auth->get_authorization_info($authCode);//获取授权方信息
        }

        //获取数据：
    }

    /**
     * 文章详情页面
     */
    public function actionArticle_details()
    {
        $this->layout = false;

        $this->view->title = '文章详情';
        $data = (new MainModel())->actionArticleDetails();

        return $this->render($data['tpl'], [
            'data'=>$data['list']
        ]);

    }
}